<template>
  <div class="application-records">
    <!-- 页面头部 -->
    <div class="page-header">
      <h2>投递记录</h2>
      <div class="header-actions">
        <el-button :icon="Refresh" @click="fetchApplicationRecords">刷新</el-button>
      </div>
    </div>

    <!-- 投递记录列表 -->
    <el-card class="records-card">
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading" :size="40"><Loading /></el-icon>
        <p>加载中...</p>
      </div>

      <div v-else-if="applicationRecords.length === 0" class="empty-state">
        <el-empty description="暂无投递记录">
          <el-button type="primary" @click="$router.push('/frontend/job-list')">
            去投递岗位
          </el-button>
        </el-empty>
      </div>

      <el-table v-else :data="applicationRecords" style="width: 100%">
        <el-table-column prop="job.jobName" label="岗位名称" width="200" />
        <el-table-column prop="job.enterprise.enterpriseName" label="公司名称" width="200" />
        <el-table-column prop="resumeName" label="投递简历" width="180" />
        <el-table-column prop="applyTime" label="投递时间" width="180">
          <template #default="{ row }">
            {{ formatTime(row.applyTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getApplyStatusType(row.status)">
              {{ getApplyStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button size="small" @click="handleViewApplyDetail(row)">查看详情</el-button>
              <el-button 
                v-if="row.status === 'pending'" 
                size="small" 
                type="success" 
                @click="handleApprove(row)"
              >
                批准
              </el-button>
              <el-button 
                v-if="row.status === 'pending'" 
                size="small" 
                type="danger" 
                @click="handleReject(row)"
              >
                驳回
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 投递详情对话框 -->
    <ApplyDetailDialog
      v-model:visible="applyDetailVisible"
      :application-data="currentApplyDetail"
      @withdraw="handleWithdrawApplication"
      @update:visible="handleApplyDetailClose"
    />

    <!-- 确认操作对话框 -->
    <el-dialog
      v-model="confirmDialogVisible"
      :title="confirmDialogTitle"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="confirm-content">
        <div class="confirm-icon">
          <el-icon :size="48" :color="confirmDialogIconColor">
            <component :is="confirmDialogIcon" />
          </el-icon>
        </div>
        <div class="confirm-message">
          {{ confirmDialogMessage }}
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button
            :type="confirmDialogType"
            :loading="confirmLoading"
            @click="handleConfirmAction"
          >
            {{ confirmDialogButtonText }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Loading, Warning, SuccessFilled, CircleClose } from '@element-plus/icons-vue'
import ApplyDetailDialog from '@/components/job/ApplyDetailDialog.vue'
import { getEnterpriseApplications, updateApplicationStatus, withdrawApplication } from '@/api/enterprise'
import useStore from '@/store'

const store = useStore()

// 投递记录数据
const applicationRecords = ref([])
const loading = ref(false)

// 对话框状态
const applyDetailVisible = ref(false)
const currentApplyDetail = ref(null)
const confirmDialogVisible = ref(false)
const confirmLoading = ref(false)
const currentConfirmApplication = ref(null)
const confirmDialogTitle = ref('')
const confirmDialogMessage = ref('')
const confirmDialogIcon = ref('Warning')
const confirmDialogIconColor = ref('#e6a23c')
const confirmDialogButtonText = ref('确定')
const confirmDialogType = ref('primary')
const currentConfirmAction = ref('')  // 'approve' 或 'reject'

// 获取投递记录 - 获取投递到本企业的记录
const fetchApplicationRecords = async () => {
  loading.value = true
  try {
    const enterpriseId = store.app.enterpriseId
    if (!enterpriseId) {
      console.warn('未找到企业ID，无法获取投递记录')
      ElMessage.warning('未找到企业信息')
      applicationRecords.value = []
      return
    }

    // 调用获取企业投递记录的API
    const response = await getEnterpriseApplications(enterpriseId, { 
      page: 1,
      pageSize: 100
    })
    
    applicationRecords.value = response?.data?.list || response?.list || []
    console.log(`✅ 获取到企业 ${enterpriseId} 的投递记录：${applicationRecords.value.length} 条`)
  } catch (error) {
    console.error('获取投递记录失败:', error)
    ElMessage.error('获取投递记录失败，请重试')
    applicationRecords.value = []
  } finally {
    loading.value = false
  }
}

// 查看投递详情
const handleViewApplyDetail = (record) => {
  console.log('查看投递详情:', record)
  currentApplyDetail.value = record
  applyDetailVisible.value = true
}

// 处理投递详情对话框关闭
const handleApplyDetailClose = () => {
  console.log('关闭投递详情对话框')
  currentApplyDetail.value = null
  applyDetailVisible.value = false
}

// 批准投递
const handleApprove = (application) => {
  currentConfirmApplication.value = application
  currentConfirmAction.value = 'approve'
  confirmDialogTitle.value = '批准投递'
  confirmDialogMessage.value = `确定要批准 ${application.job?.jobName} 的投递申请吗？`
  confirmDialogIcon.value = 'SuccessFilled'
  confirmDialogIconColor.value = '#67c23a'
  confirmDialogButtonText.value = '确定批准'
  confirmDialogType.value = 'success'
  confirmDialogVisible.value = true
}

// 驳回投递
const handleReject = (application) => {
  currentConfirmApplication.value = application
  currentConfirmAction.value = 'reject'
  confirmDialogTitle.value = '驳回投递'
  confirmDialogMessage.value = `确定要驳回 ${application.job?.jobName} 的投递申请吗？`
  confirmDialogIcon.value = 'CircleClose'
  confirmDialogIconColor.value = '#f56c6c'
  confirmDialogButtonText.value = '确定驳回'
  confirmDialogType.value = 'danger'
  confirmDialogVisible.value = true
}

// 确认操作
const handleConfirmAction = async () => {
  if (!currentConfirmApplication.value || !currentConfirmAction.value) return
  
  confirmLoading.value = true
  
  try {
    const applicationId = currentConfirmApplication.value.applicationId
    const action = currentConfirmAction.value
    
    if (action === 'approve') {
      // 批准 - 更新状态为 interviewing（面试中）
      await updateApplicationStatus(applicationId, 'interviewing')
      
      ElMessage.success('已批准投递申请，状态已更新为面试中')
    } else if (action === 'reject') {
      // 驳回 - 更新状态为 rejected（已拒绝）
      await updateApplicationStatus(applicationId, 'rejected')
      
      ElMessage.success('已驳回投递申请')
    }
    
    confirmDialogVisible.value = false
    
    // 刷新列表
    await fetchApplicationRecords()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败，请重试')
  } finally {
    confirmLoading.value = false
  }
}

// 撤回投递（从详情对话框调用）
const handleWithdrawApplication = async (applicationId) => {
  try {
    // 调用撤回投递的API
    await withdrawApplication(applicationId)
    
    ElMessage.success('投递已撤回')
    
    // 刷新列表
    await fetchApplicationRecords()
  } catch (error) {
    console.error('撤回投递失败:', error)
    ElMessage.error(error.message || '撤回投递失败，请重试')
  }
}

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '-'
  const date = new Date(timeString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取投递状态类型
const getApplyStatusType = (status) => {
  const typeMap = {
    pending: 'warning',
    reviewing: 'primary',
    interviewing: 'primary',
    accepted: 'success',
    rejected: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取投递状态文本
const getApplyStatusText = (status) => {
  const textMap = {
    pending: '待处理',
    reviewing: '审核中',
    interviewing: '面试中',
    accepted: '已通过',
    rejected: '已拒绝'
  }
  return textMap[status] || '未知'
}

// 页面加载时获取数据
onMounted(() => {
  fetchApplicationRecords()
})
</script>

<style scoped>
.application-records {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.15);
}

.page-header h2 {
  margin: 0;
  color: #fff;
  font-size: 24px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.records-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #666;
}

.loading-container p {
  margin-top: 12px;
  font-size: 14px;
}

.empty-state {
  padding: 40px 20px;
  text-align: center;
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 确认对话框样式 */
.confirm-content {
  text-align: center;
  padding: 20px 0;
}

.confirm-icon {
  margin-bottom: 16px;
}

.confirm-message {
  font-size: 16px;
  color: #333;
  line-height: 1.5;
}

.dialog-footer {
  text-align: right;
}
</style>

